package Control;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;

import Entity.Shop_Order;
import Entity.Shop_Order_StatusCode;
import Entity.User;
import Form.Shop_AdministrateOrders_Form;

public class Shop_AdministrateOrder_Controller {
	
	private Shop_AdministrateOrders_Form parser;
	private ArrayList<Shop_Order> orderList;
	
	public Shop_AdministrateOrder_Controller(Shop_AdministrateOrders_Form parser){
		this.parser = parser;
		
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){

			@Override
			protected Void doInBackground() throws Exception {
				orderList = Shop_Order.getAllOrders();
				return null;
			}
			
			protected void done(){
				
				JScrollPane scrollPane = getParser().getOrdersPane();

				JPanel panel = new JPanel();
				panel.setPreferredSize(new Dimension(560, orderList.size() * 140));
				for(int a = 0; a < orderList.size(); a++){
					final int tempA = a;
					
					Color background;
					Color foreground;
					if(a % 2 == 0){
						foreground = Color.DARK_GRAY;
						background = Color.LIGHT_GRAY;
					}
					else{
						background = Color.DARK_GRAY;
						foreground = Color.LIGHT_GRAY;
					}
					
					JPanel holder = new JPanel();
					holder.setBackground(background);
					holder.setPreferredSize(new Dimension(540, 130));
					FlowLayout layout = (FlowLayout)holder.getLayout();
					layout.setAlignment(FlowLayout.LEFT);
					
					JLabel orderId = new JLabel(orderList.get(a).getOrderId());
					orderId.setForeground(foreground);
					orderId.setFont(new Font("Segoe UI Light", Font.BOLD, 20));
					orderId.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 20, background));
					holder.add(orderId);
					
					JLabel orderStatus = new JLabel();
					orderStatus.setOpaque(true);
					
					Color colorCode;
					Color text;
					final String status;
					if(orderList.get(a).getStatusCode().getOrderStatusCode().equals("RDY")){
						orderStatus.setText("Ready");
						status = "Ready";
						colorCode = Color.GREEN;
						text = Color.BLACK;
					}
					else if(orderList.get(a).getStatusCode().getOrderStatusCode().equals("PEN")){
						orderStatus.setText("Pending");
						status = "Pending";
						colorCode = Color.BLUE;
						text = Color.WHITE;
					}
					else if(orderList.get(a).getStatusCode().getOrderStatusCode().equals("ACP")){
						orderStatus.setText("Accepted");
						status = "Accepted";
						colorCode = Color.PINK;
						text = Color.BLACK;
					}
					else{
						orderStatus.setText("Collected");
						status = "Collected";
						colorCode = Color.WHITE;
						text = Color.BLACK;
					}
					orderStatus.setBackground(colorCode);
					orderStatus.setBorder(BorderFactory.createMatteBorder(5, 20, 5, 20, colorCode));
					orderStatus.setForeground(text);
					orderStatus.addMouseListener(new MouseListener(){

						@Override
						public void mouseClicked(MouseEvent arg0) {
							Object [] statusCodes = {"Ready", "Accepted", "Pending", "Collected"};
							String response = (String)JOptionPane.showInputDialog(getParser().getParser(), "Select status of order:", "Status", JOptionPane.PLAIN_MESSAGE, null, statusCodes, status);
							if(response != null && response.length() > 0){
								if(response.equals("Ready"))
									orderList.get(tempA).setStatusCode(new Shop_Order_StatusCode("RDY"));
								else if(response.equals("Accepted")){
									orderList.get(tempA).setStatusCode(new Shop_Order_StatusCode("ACP"));
									ArrayList<User> residents = Shop_Order.getPossibleNeedy(orderList.get(tempA));
									Object [] residentsArr = new Object[residents.size()];
									for(int i = 0; i < residents.size(); i++){
										residentsArr[i] = residents.get(i).getNric();
									}
									String resident = (String)JOptionPane.showInputDialog(getParser().getParser(), "Select Needy Resident for job:", "Assign Job", JOptionPane.PLAIN_MESSAGE, null, residentsArr, residentsArr[0]);
									if(resident != null){
										orderList.get(tempA).acceptOrder(resident);
									}
								}
								else if(response.equals("Pending"))
									orderList.get(tempA).setStatusCode(new Shop_Order_StatusCode("PEN"));
								else
									orderList.get(tempA).setStatusCode(new Shop_Order_StatusCode("COL"));
								
								if(orderList.get(tempA).updateOrderStatus()){
									getParser().getParser().displayMessage(true, "Successfully updated status of order, " + orderList.get(tempA).getOrderId() + ".\nStatus changed: " + response + ".");
									getParser().remove(getParser().getOrdersPane());
									getParser().setOrdersPane(null);
									getParser().add(getParser().getOrdersPane());
								}
								else{
									getParser().getParser().displayMessage(false, "Error encountered while updating status of order. Please try again in awhile.");
								}
							}
						}

						@Override
						public void mouseEntered(MouseEvent arg0) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void mouseExited(MouseEvent arg0) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void mousePressed(MouseEvent arg0) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void mouseReleased(MouseEvent arg0) {
							// TODO Auto-generated method stub
							
						}
						
					});
					holder.add(orderStatus);
					
					if(orderList.get(a).getStatusCode().getOrderStatusCode().equals("ACP")){
						JLabel takeJob = new JLabel("Job taken up: " + orderList.get(a).getNeedyNric());
						takeJob.setFont(new Font("Segoe UI Light", Font.PLAIN, 15));
						takeJob.setForeground(foreground);
						takeJob.setBorder(BorderFactory.createMatteBorder(0, 20, 0, 0, background));
						holder.add(takeJob);
					}
					
					JSeparator headerSplit = new JSeparator();
					headerSplit.setForeground(foreground);
					headerSplit.setPreferredSize(new Dimension(530, 5));
					holder.add(headerSplit);
					
					JPanel datesHolder = new JPanel();
					datesHolder.setBackground(foreground);
					datesHolder.setPreferredSize(new Dimension(300, 50));
					layout = (FlowLayout)datesHolder.getLayout();
					layout.setAlignment(FlowLayout.LEFT);
					
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
					
					JLabel orderDate = new JLabel("Ordered on: " + sdf.format(orderList.get(a).getOrderDate()));
					orderDate.setFont(new Font("Segoe UI Light", Font.BOLD, 12));
					orderDate.setForeground(background);
					datesHolder.add(orderDate);
					
					JLabel collectDate = new JLabel("Collection date(Tentative): " + sdf.format(orderList.get(a).getCollectDate()));
					collectDate.setFont(new Font("Segoe UI Light", Font.BOLD, 12));
					collectDate.setForeground(background);
					datesHolder.add(collectDate);
					
					holder.add(datesHolder);
					
					JSeparator split = new JSeparator();
					split.setForeground(foreground);
					split.setOrientation(SwingConstants.VERTICAL);
					split.setPreferredSize(new Dimension(5, 50));
					holder.add(split);
					
					JPanel ordersHolder = new JPanel();
					ordersHolder.setOpaque(false);
					ordersHolder.setPreferredSize(new Dimension(200, 50));
					layout = (FlowLayout)ordersHolder.getLayout();
					layout.setAlignment(FlowLayout.LEFT);
					
					JLabel ordersTxt = new JLabel("Orders:");
					ordersTxt.setForeground(foreground);
					ordersTxt.setFont(new Font("Segoe UI Light", Font.BOLD, 15));
					ordersHolder.add(ordersTxt);
					
					final JComboBox orders = new JComboBox();
					orders.setPreferredSize(new Dimension(100, 20));
					for(int b = 0; b < orderList.get(a).getCustomizations().size(); b++){
						orders.addItem(orderList.get(a).getCustomizations().get(b).getCustId());
					}
					orders.setSelectedIndex(0);
					orders.addActionListener(new ActionListener(){

						@Override
						public void actionPerformed(ActionEvent arg0) {
							JDialog preview = new JDialog(getParser().getParser(), true);
							JTabbedPane previewTabs = new JTabbedPane();
							
							JLabel front = new JLabel();
							front.setPreferredSize(new Dimension(300, 400));
							front.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(orderList.get(tempA).getCustomizations().get(orders.getSelectedIndex()).getFrontCustUrl()).getScaledInstance(300, 400, Image.SCALE_DEFAULT)));
							previewTabs.addTab("Front", front);
							
							JLabel back = new JLabel();
							back.setPreferredSize(new Dimension(300, 400));
							back.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(orderList.get(tempA).getCustomizations().get(orders.getSelectedIndex()).getBackCustUrl()).getScaledInstance(300, 400, Image.SCALE_DEFAULT)));
							previewTabs.addTab("Back", back);
							
							preview.add(previewTabs);
							
							preview.pack();
							preview.setLocationRelativeTo(getParser().getParser());
							preview.setVisible(true);
						}
						
					});
					ordersHolder.add(orders);
					
					JLabel totalPrice = new JLabel();
					totalPrice.setText("Total price: $" + orderList.get(a).getTotalPrice());
					totalPrice.setForeground(foreground);
					totalPrice.setFont(new Font("Segoe UI Light", Font.BOLD, 15));
					ordersHolder.add(totalPrice);
					
					holder.add(ordersHolder);
					
					panel.add(holder);
				}
				scrollPane.getViewport().add(panel);
				
				getParser().getParser().closeProgressBar();
			}
			
		};
		getParser().getParser().getProgressBar();
		worker.execute();
	}

	public Shop_AdministrateOrders_Form getParser() {
		return parser;
	}

	public void setParser(Shop_AdministrateOrders_Form parser) {
		this.parser = parser;
	}

}
